import type { Ref } from "vue";
import type { DictTypeDetailResult, DictTypeListResult } from "@/api/types";
import { ref } from "vue";
import { dictTypeApi } from "@/api";
import { apiCall } from "@/utils/http/apiCall";

interface UseDictTypeFormDialog {
    /** 对话框状态 */
    dialogVisible: Ref<boolean>;
    /** 当前编辑的字典类型详情 */
    typeDetail: Ref<DictTypeDetailResult | null>;
    /** 打开新增 */
    openAddDialog: () => void;
    /** 打开编辑 */
    openEditDialog: (row: DictTypeListResult) => void;
}

export function useDictTypeFormDialog(): UseDictTypeFormDialog {
    /** 对话框状态 */
    const dialogVisible = ref(false);
    /** 当前编辑行 */
    const typeDetail = ref<DictTypeDetailResult | null>(null);

    /** 打开新增 */
    function openAddDialog(): void {
        typeDetail.value = null;
        dialogVisible.value = true;
    }

    /** 打开编辑 */
    function openEditDialog(row: DictTypeListResult): void {
        apiCall(
            () => dictTypeApi.findById(row.id),
            (data) => {
                typeDetail.value = data;
                dialogVisible.value = true;
            },
        );
    }

    return {
        dialogVisible,
        typeDetail,
        openAddDialog,
        openEditDialog,
    };
}
